<template>
	<view v-if="refreshed">
        <image class="viewImage" :src="urlto" v-if="isImage" mode="widthFix"></image>
		<web-view :webview-styles="webviewStyles" :src="urlto"  class="iframepage" @message="onGetMessage" v-else></web-view>
	</view>
</template>

<script>
	import sceneMixins from '@/utils/sceneMixins.js';
	import getLocation from '@/utils/getLocation.js'
	export default {
		data() {
			return {
				urlto:'',
                isImage: true,
				webviewStyles: {
					progress: {
						color: '#FF3333'
					}
				},
				refreshed: true
			
			}
		},
		mixins:[sceneMixins, getLocation],
		onShow: function () {
			if (this.needRefresh) {
				this.refreshed = false;
				setTimeout(() => {
					this.refreshed = true;
				}, 200);
			}
		},
		onLoad(options) {
			var vm = this;
			if (options.title) {
				uni.setNavigationBarTitle({
					title: options.title
				});
				vm.title = options.title;
			}
	
            var url = decodeURIComponent(options.url);
			if (url.includes('needRefresh')) {
				this.needRefresh = true;
			}
			if (url.includes('【openId】')) {
				vm.needAutho = true;
			}
			if (url.includes('【accessToken】')) {
				vm.needAutho = false;
			}

            vm.isImage = url.endsWith('.png');
			vm.waitVariable('userType').then(userType => {
				// console.log('/pages/index/index?scene=' + encodeURIComponent(`openh5$${encodeURIComponent(url)}`) );
				if ((url.includes('【userName】') || url.includes('【sfzh】') || url.includes('【phone】')) && userType == 'tempUser') { // 临时用户重新进来
					uni.redirectTo({
						url: '/pages/index/index?scene=' + encodeURIComponent(`openh5$${encodeURIComponent(url)}`) 
					})
					return;
				}
				vm.doWxLogin().then(async res => {
					console.log('urlOrign', url);
					url = url.replace('【openId】', res.openId)
					.replace('【timeStamp】', new Date().getTime())
					.replace('【userName】', this.$store.state.userInfo && this.$store.state.userInfo.userName)
					.replace('【sfzh】', this.$store.state.userInfo && this.$store.state.userInfo.credentialsNo)
					.replace('【phone】', this.$store.state.userInfo && this.$store.state.userInfo.phone)
					.replace('【accessToken】',  uni.getStorageSync('accessToken'));

					if (url.includes('【lnglat】')) {
						await vm.getUserLocation();
						url = url.replace('【lnglat】', this.$store.state.lnglat)
					}


					var defaultUrlPrefix = vm.API_PREFIX;
					// #ifdef MP-WEIXIN
					if (__wxConfig.envVersion != 'develop') {
						defaultUrlPrefix = defaultUrlPrefix.replace(/:[1-9]\d*/, '');
					}
					url = (url.startsWith('http') ? '' : defaultUrlPrefix) + url;
					console.log(url);

					// debugger
					if (!(url.includes('dashboard.html') || url.includes('accessToken')) && (vm.needAutho || url.includes(res.openId))) {
						url = vm.API_PREFIX + '/mobile/h5/huizetong/dashboard.html?url=' + encodeURIComponent(url) + '&accessToken=' + uni.getStorageSync('accessToken');
						console.log(url)
					}

					this.urlto = url;
					// #endif
					
					// #ifdef H5
					if (location.hostname != 'localhost') {
						defaultUrlPrefix = defaultUrlPrefix.replace(/:[1-9]\d*/, '');
					}
					console.log(url);
					if (url.includes('needWebview')) {
						this.urlto = url;
					} else {
						location.href = url;
					}
					// #endif
				
				});
			});
			
		},
		methods: {
			onGetMessage: function (data) {
				var val = data.detail.data[0];
				if (val && val.downloadbase64) {
					this.saveImageToPhotosAlbum(val.downloadbase64);
				} else if (val && val.daohang) {
					uni.openLocation({
						...JSON.parse(val.daohang)
					});
				} else if (val && val.listPageNeedUpdate) {
					global.listPageNeedReload = true;
				}				
			},
			saveImageToPhotosAlbum(base64Str){
                var vm = this;
                let base64=base64Str.replace(/^data:image\/\w+;base64,/, "");//去掉data:image/png;base64,
                let filePath=wx.env.USER_DATA_PATH + '/hym_pay_qrcode.png';
                uni.getFileSystemManager().writeFile({
                    filePath:filePath ,  //创建一个临时文件名
                    data: base64,    //写入的文本或二进制数据
                    encoding: 'base64',  //写入当前文件的字符编码
                    success: res => {
                        uni.saveImageToPhotosAlbum({
                            filePath: filePath,
                            success: function(res2) {
                                uni.showToast({
                                    title: '保存成功，请从相册选择再分享',
                                    icon:"none",
                                    duration:5000
                                })
								uni.navigateTo({
								    url: '/pages/openh5/index?title=' + vm.title + '&url=' + encodeURIComponent(vm.urlto)
								})
                            },
                            fail: function(err) {
                                // console.log(err.errMsg);
                            }
                        })
                    },
                    fail: err => {
                        //console.log(err)
                    }
                })
            }
        },
		
	}
</script>

<style lang="scss" scoped>
.viewImage {
    width: 750rpx;
}
</style>